package org.redtroy.theater.service.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.redtroy.theater.bean.User;
import org.redtroy.theater.dao.hibernate.UserDAO;
import org.redtroy.theater.service.IUserService;
import org.redtroy.theater.service.dto.UserDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

@Service(value = "userService")
public class UserService implements IUserService {
	@Autowired
	@Qualifier(value = "userDAO")
	private UserDAO userDAO;

	@Transactional(propagation = Propagation.REQUIRED)
	public User create(UserDTO user) throws Exception {
		Criteria criteria = userDAO.createCriteria();
		if (StringUtils.hasText(user.getEmail()))
			criteria.add(Restrictions.eq("email", user.getEmail()));
		if (StringUtils.hasText(user.getNickName()))
			criteria.add(Restrictions.eq("nickName", user.getNickName()));
		User savedUser = (User) criteria.uniqueResult();
		if (savedUser != null)
			return savedUser;
		User user2 = new User();
		BeanUtils.copyProperties(user, user2);
		return userDAO.persist(user2);
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public List<User> listAll() throws Exception {
		return userDAO.listAll();
	}

	@Transactional(readOnly = true)
	public User getUserByEmail(String email) throws Exception {
		Assert.hasText(email, "Email cannot be empty!");
		Criteria criteria = userDAO.createCriteria();
		criteria.add(Restrictions.eq("email", email));
		return (User) criteria.uniqueResult();
	}

}
